package com.openweixin.sheknows.service.impl;

import java.io.File;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.task.TaskExecutor;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import com.openweixin.sheknows.service.MailService;

/**
 * 描述：发送邮件的工具类
 * 
 * @author 刘思作
 * @version 1.0.0, 2014-03-21
 * @since v1.0.0
 */

@Service
public class MailServiceImpl implements MailService {

	@Resource
	private JavaMailSenderImpl javaMailSender;
	@Resource
	private TaskExecutor taskExecutor;
	
	@Value("#{settings['mail.host']}")
	private String host;
	
	@Value("#{settings['mail.port']}")
	private Integer port;
	
	@Value("#{settings['mail.username']}")
	private String username;
	
	@Value("#{settings['mail.password']}")
	private String password;
	
	@Value("#{settings['mail.encode']}")
	private String encode;

	// 增加邮件发送任务
	public void addSendMailTask(final MimeMessage mimeMessage) {
		try {
			taskExecutor.execute(new Runnable() {
				public void run() {
					javaMailSender.send(mimeMessage);
				}
			});
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void sendMail(String subject, String templateFilePath,
			String content, String toMail) {
		try {
			JavaMailSenderImpl javaMailSenderImpl = (JavaMailSenderImpl) javaMailSender;
			javaMailSenderImpl.setHost(host);
			javaMailSenderImpl.setPort(port);
			javaMailSenderImpl.setUsername(username);
			javaMailSenderImpl.setPassword(password);
			MimeMessage mimeMessage = javaMailSenderImpl.createMimeMessage();
			
			MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(
					mimeMessage, false, encode);
			
			mimeMessageHelper.setFrom(javaMailSender.getUsername());
			mimeMessageHelper.setTo(toMail);
			mimeMessageHelper.setSubject(subject);
			mimeMessageHelper.setText(content, true);
			if (!StringUtils.isEmpty(templateFilePath)) {
				String filename = templateFilePath.substring(templateFilePath
						.lastIndexOf("/") + 1);
				mimeMessageHelper.addAttachment(filename, new File(
						templateFilePath));
			}
			addSendMailTask(mimeMessage);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}